<template>
    <a-select v-model:value="props.question.value" 
    :disabled="props.question.disabled"
    :options="props.question.options"
    :dropdownStyle="{ 'display': 'none' }" 
    :placeholder="props.question.placeholder" 
    :multiple="props.question.state.multiple ? true: false" 
    @click="selectId()"  >
    </a-select>
    <a-form-item-rest>
      <div ref="treeModal" v-if="visible">
        <a-modal :getContainer="() => $refs.treeModal" v-model:visible="visible" :title="props.question.state.title || '请选择'" :width="1200"  @cancel="cancel" @ok="handleOk">
          <div class="tree_modal_wrap">
            <div class="tree_modal_left">
              <a-tree v-if="treeData.length" 
                class="tree-warpper" 
                v-model:selectedKeys="selectedKeys" 
                :tree-data="treeData" 
                show-icon 
                :fieldNames="props.question.state.fieldNames"
                :load-data="props.question.state.loadData ? onLoadData : null"
                :block-node="true" 
                tree-node-label-prop="path"
                tree-node-filter-prop="name"
                @select="treeSelect">
              </a-tree>
            </div>
            <div class="tree_modal_right">
              <DynamicTable ref="treeDictionaryTableRef" :tables="tables" :config="config" :icons="[]" >
              </DynamicTable>
            </div>
          </div>
        </a-modal>
      </div>
    </a-form-item-rest>
</template>
<script lang="ts" setup>
import {ref,reactive, onMounted,getCurrentInstance, onUnmounted } from 'vue'
import { DynamicTable, TableBase} from '@/components/public-template';
import { Subscription } from 'rxjs';
import { message } from 'ant-design-vue';

let $subscribeSub: Subscription;

const emit = defineEmits(['update:value']);
const props = defineProps<{  question:any}>()
const { proxy }: any = getCurrentInstance();

const selectValue = ref({});

const selectId = ()=>{
  if( props.question.value ){
    selectedKeys.value = [props.question.value];
  }
  visible.value  = true;
  init();
}

const cancel=()=>{
  selectValue.value = {};
  selectedKeys.value =[];
  visible.value  = false;
}
//提交
const handleOk=()=>{
  let value = selectedKeys.value[0];
  if( treeDictionaryTableRef.value.selectedRowIndex ){  //判断右边有值没
    let obj = treeDictionaryTableRef.value.dataList.value.find((res)=>res[props.question.state.config.rowKey || 'id'] === treeDictionaryTableRef.value.selectedRowIndex);
    value = { label: obj[props.question.state.tableLabelKey || 'name'], value: treeDictionaryTableRef.value.selectedRowIndex};
  }else if(props.question.state.isRight){ //只能选右边
    return message.warning('必须选择右边表格数据')
  }

  //开始赋值
  let option = selectValue.value;
  props.question.value = value;
  props.question.options = [option];
  cancel();
}


const visible:any = ref(false);
let tables: TableBase<any>[] = reactive(props.question.state.getTables);
let config: any = reactive(props.question.state.config);
//tree
let treeData = ref([]);
const selectedKeys = ref([]);

onMounted(()=>{
})

const init = ()=>{
  if( props.question.state.url ){
    let params = Object.assign({}, props.question.state.params);
    proxy.$Http.api( props.question.state.url, params, props.question.state.protType ? props.question.state.protType : 'get' ).then((res)=>{
      if( res && res.data ){
        treeData.value = res.data;
      }
    })
  }
}

//选择右边数据显示表单
const treeDictionaryTableRef = ref();
const treeSelect = (selectedKeys,e) => {
  selectValue.value = {
    label: e.node[props.question.state.fieldNames.title],
    value: selectedKeys[0]
  }
  config.params.typeId = selectedKeys[0];
  treeDictionaryTableRef.value.selectedRowIndex = null;
  treeDictionaryTableRef.value.getData();
};


//解绑
onUnmounted(() => {
  if ($subscribeSub != undefined) {
    $subscribeSub.unsubscribe();
  }
  console.log('准备离开tree-modal');
});

//仓库异步调用
const onLoadData = (treeNode) => {
  return new Promise((resolve) => {
    if (treeNode.dataRef[props.question.state.fieldNames.children]) {
      resolve(true);
      return;
    }
    getWarehouseTreeData(null, treeNode.dataRef.id, treeNode.dataRef.type, (data) => {
      if( data ){
        treeNode.dataRef[props.question.state.fieldNames.children] = data;
        treeData.value = [...treeData.value];
        resolve(true);
      }else{
        treeNode.dataRef.isLeaf = true;
        resolve(true);
      }
    });
  });
}
// 获取仓库树
function getWarehouseTreeData(name = null, parentId = null, type = null, callback = null) {
  let childKey = props.question.state.fieldNames.children;
  let params = Object.assign({
    name,
    parentId,
    type
  }, props.question.state.subParams || {});
    proxy.$Http.api(  props.question.state.url, params,  props.question.state.protType || 'post' ).then((res)=>{
      if( res && res.data ){
        let data = handleTreeData(res.data, res.data, childKey, props.question.state.disabledType || []);
        if (callback) {
          callback(data);
        } else {
          treeData.value = data;
        }
      }else{
        callback(null)
      }
    })
}
// 处理树结构数据
function handleTreeData(data = [], orgData = [], childKey = 'children', disabledType = []) {
  data.forEach((item) => {
    if (disabledType.includes(item.type)) {
      item.disabled = true;
    }
    item.path =
      item.parentId === '0' ? item.name : getFullPath(orgData, item.parentId, childKey).concat(item.name).join('/');
    item.isLeaf = Boolean(item.isLeaf);
    if (item[childKey] && item[childKey].length) {
      item.children = item[childKey];
      handleTreeData(item[childKey], orgData, childKey, disabledType);
    }
  });
  return data;
}
// 获取完整的文本路径
function getFullPath(data, parentId, childKey = 'children') {
  let result = [];
  let isFinish = false;
  let traverse = (parentId, path, data) => {
    if (data.length === 0 || isFinish) {
      return;
    }
    for (let item of data) {
      if (item.parentId === parentId) {
        result = path;
        isFinish = true;
        return;
      }
      path.push(item.name);
      const children = Array.isArray(item[childKey]) ? item[childKey] : [];
      traverse(parentId, path, children);
      if (isFinish) {
        return;
      }
      path.pop();
    }
  };
  traverse(parentId, [], data);
  return result;
}
</script>
<style lang="less" scoped>
.tree_modal_wrap{
  display: flex;
  .tree_modal_left{
    width: 317px;
    flex-shrink: 0;
    border-right: 1px solid rgba(0,0,0,0.09);
  }
  .tree_modal_right{
    padding-left: 20px;
  }
}
</style>
